const db = require('../../database')
const crypto = require('crypto')

/**
 * 对密码进行加密
 * @param password
 * @param salt
 * @returns {string}
 */
const getHash = (password, salt) => {
  return crypto.pbkdf2Sync(password, salt, 100000, 256, 'sha256').toString('hex')
}
/**
 * 添加新用户
 * @param user
 * @param done
 * @returns {*}
 */
const addNewUser = (user, done) => {
  console.log('currentPassword', user.password)
  if (!user.password) return done('密码不能为空', null)
  const salt = crypto.randomBytes(64)
  const hash = getHash(user.password, salt)

  const sql = 'INSERT INTO users (username,password,email,nickname,salt) VALUES (?,?,?,?,?)'
  let values = [user.username, hash, user.email, user.email, salt.toString('hex')]

  db.query(sql, values, function (err, results) {
    if (err) {
      return done(err, null)
    }
    return done(null, results.insertId)
  })
}

const getEmailById = (user_id, done) => {

  console.log('user_email', user_id)
  const sql = 'select email from users where user_id=?'

  db.query(sql, [user_id], function (err, row) {
    if (err) {
      console.log('err', err)
      return done(err, null)
    }
    return done(null, row)
  })
}

/**
 * 用户登录的验证功能
 * @param username
 * @param password
 * @param done
 */
const authenticateUser = (username, password, done) => {
  const sql = 'SELECT user_id,password,salt FROM users WHERE username=?'

  db.query(sql, [username], (err, results) => {
    //查询数据失败
    if (err) return done(err['sqlMessage'])
    //查询数据成功，但是没有找到数据
    if (results.length === 0) return done({ msg: 'not found this user' })
    let result = results[0]
    if (result.salt === null) result.salt = ''
    let salt = Buffer.from(result.salt, 'hex')
    //密码验证成功
    if (result.password === getHash(password, salt)) {
      return done(null, result.user_id)
    } else {
      //密码验证失败
      return done({ msg: 'password is invalid' })
    }
  })
}

/**
 * 设置token
 * @param id
 * @param done
 */
const setToken = (id, done) => {
  let token = crypto.randomBytes(16).toString('hex')

  const sql = 'UPDATE users SET session_token=? WHERE user_id=?'

  db.query(sql, [token, id], (err) => {
    return done(err, token)
  })
}

/**
 * 获取token
 * @param id
 * @param done
 */
const getToken = (id, done) => {
  const sql = 'SELECT session_token FROM users WHERE user_id = ?'

  db.query(sql, [id], (err, row) => {
    if (err) {
      return done(err, null)
    }
    if (row.length===0 || !row[0].session_token) {
      return done('Token not found for the specified user ID', null)
    }

    const token = row[0].session_token
    return done(null, token)
  })
}

/**
 * 移除token
 * @param token
 * @param done
 */
const removeToken = (token, done) => {
  const sql = 'UPDATE users SET session_token=null WHERE session_token=?'

  db.query(sql, [token], function (err, results) {
    if (err) return done(err, null)
    if (results.changedRows === 0) {
      return done({ msg: 'token is valid' }, null)
    }
    return done(null, { msg: 'logout success' })
  })
}

/**
 * 根据token获取用户id
 * @param token
 * @param done
 */
const getIDFromToken = (token, done) => {
  const sql = 'SELECT user_id FROM users WHERE session_token = ?'

  db.query(sql, [token], (err, results) => {
    if (err) {
      return done(err, null)
    }
    if (results.length === 0) {
      return done(new Error('Invalid token or user not found'), null)
    }

    const userId = results[0].user_id
    return done(null, userId)
  })
}

/**
 * 获取所有用户
 * @param done
 */
const getAllUsers = (done) => {
  const sql = 'SELECT * FROM users '

  db.query(sql, (err, users) => {
    if (err) {
      done(err, null)
    } else {
      done(null, users)
    }
  })
}

/**
 * 根据用户id获取单个用户
 * @param user_id
 * @param done
 */
const getUserById = (user_id, done) => {
  const sql = 'SELECT * FROM users where user_id=?'

  db.query(sql, [user_id], (err, results) => {
    if (err) return done(err, null)
    if (results.length === 0) return done({ msg: 'not found' })
    return done(null, [{
      username: results[0].username,
      nickname: results[0].nickname,
      email: results[0].email
    }])

  })
}
module.exports = {
  addNewUser,
  authenticateUser,
  setToken,
  getToken,
  removeToken,
  getIDFromToken,
  getEmailById,
  getAllUsers,
  getUserById
}
